home *** CD-ROM | disk | FTP | other *** search
/ InfoMagic Internet Tools 1993 July / Internet Tools.iso / RockRidge / mail / pine / pine3.07 / c-client / os_hpp.c < prev    next >
Encoding:
C/C++ Source or Header  |  1993-03-29  |  20.9 KB  |  774 lines

  1. /*
  2.  * Program:    Operating-system dependent routines -- HP/UX version
  3.  *
  4.  * Author:    David L. Miller
  5.  *        Computing and Telecommunications Center
  6.  *        Washington State University Tri-Cities
  7.  *        Richland, WA 99352
  8.  *        Internet: dmiller@beta.tricity.wsu.edu
  9.  *
  10.  * Date:    10 April 1992
  11.  * Last Edited:    28 May 1992/maintenance release 29 March 1993
  12.  *
  13.  * Copyright 1992 by the University of Washington
  14.  *
  15.  *  Permission to use, copy, modify, and distribute this software and its
  16.  * documentation for any purpose and without fee is hereby granted, provided
  17.  * that the above copyright notice appears in all copies and that both the
  18.  * above copyright notice and this permission notice appear in supporting
  19.  * documentation, and that the name of the University of Washington not be
  20.  * used in advertising or publicity pertaining to distribution of the software
  21.  * without specific, written prior permission.  This software is made
  22.  * available "as is", and
  23.  * THE UNIVERSITY OF WASHINGTON DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED,
  24.  * WITH REGARD TO THIS SOFTWARE, INCLUDING WITHOUT LIMITATION ALL IMPLIED
  25.  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, AND IN
  26.  * NO EVENT SHALL THE UNIVERSITY OF WASHINGTON BE LIABLE FOR ANY SPECIAL,
  27.  * INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  28.  * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, TORT
  29.  * (INCLUDING NEGLIGENCE) OR STRICT LIABILITY, ARISING OUT OF OR IN CONNECTION
  30.  * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  31.  *
  32.  */
  33.  
  34.  
  35. #define isodigit(c)    (((unsigned)(c)>=060)&((unsigned)(c)<=067))
  36. #define toint(c)       ((c)-'0')
  37.  
  38.  
  39. /* TCP input buffer */
  40.  
  41. #define BUFLEN 8192
  42.  
  43.  
  44. /* TCP I/O stream (must be before osdep.h is included) */
  45.  
  46. #define TCPSTREAM struct tcp_stream
  47. TCPSTREAM {
  48.   char *host;            /* host name */
  49.   char *localhost;        /* local host name */
  50.   int tcpsi;            /* input socket */
  51.   int tcpso;            /* output socket */
  52.   int ictr;            /* input counter */
  53.   char *iptr;            /* input pointer */
  54.   char ibuf[BUFLEN];        /* input buffer */
  55. };
  56.  
  57.  
  58. #include <sys/types.h>
  59. #include <sys/time.h>
  60. #include <sys/socket.h>
  61. #include <netinet/in.h>
  62. #include <netdb.h>
  63. #include <ctype.h>
  64. #include <errno.h>
  65. extern int errno;        /* just in case */
  66. #include <pwd.h>
  67. #include <syslog.h>
  68. #include <regex.h>
  69. #include "osdep.h"
  70. #include "mail.h"
  71. #include "misc.h"
  72.  
  73. /* Write current time in RFC 822 format
  74.  * Accepts: destination string
  75.  */
  76.  
  77. char *days[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
  78. char *months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
  79.         "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
  80.  
  81. void rfc822_date (date)
  82.     char *date;
  83. {
  84.   int zone;
  85.   char *zonename;
  86.   struct tm *t;
  87.   struct timeval tv;
  88.   struct timezone tz;
  89.   gettimeofday (&tv,&tz);    /* get time and timezone poop */
  90.   t = localtime (&tv.tv_sec);    /* convert to individual items */
  91.                 /* get timezone from TZ environment stuff */
  92.   zone = daylight ? -timezone/60 + 60 : -timezone/60;
  93.   zonename = daylight ? tzname[1] : tzname[0] ;
  94.                 /* and output it */
  95.   sprintf (date,"%s, %d %s %d %02d:%02d:%02d %+03d%02d (%s)",
  96.        days[t->tm_wday],t->tm_mday,months[t->tm_mon],t->tm_year+1900,
  97.        t->tm_hour,t->tm_min,t->tm_sec,zone/60,abs (zone) % 60,zonename);
  98. }
  99.  
  100. /* Get a block of free storage
  101.  * Accepts: size of desired block
  102.  * Returns: free storage block
  103.  */
  104.  
  105. void *fs_get (size)
  106.     size_t size;
  107. {
  108.   void *block = malloc (size);
  109.   if (!block) fatal ("Out of free storage");
  110.   return (block);
  111. }
  112.  
  113.  
  114. /* Resize a block of free storage
  115.  * Accepts: ** pointer to current block
  116.  *        new size
  117.  */
  118.  
  119. void fs_resize (block,size)
  120.     void **block;
  121.     size_t size;
  122. {
  123.   if (!(*block = realloc (*block,size))) fatal ("Can't resize free storage");
  124. }
  125.  
  126.  
  127. /* Return a block of free storage
  128.  * Accepts: ** pointer to free storage block
  129.  */
  130.  
  131. void fs_give (block)
  132.     void **block;
  133. {
  134.   free (*block);
  135.   *block = NIL;
  136. }
  137.  
  138.  
  139. /* Report a fatal error
  140.  * Accepts: string to output
  141.  */
  142.  
  143. void fatal (string)
  144.     char *string;
  145. {
  146.   mm_fatal (string);        /* output the string */
  147.   syslog (LOG_ALERT,"IMAP C-Client crash: %s",string);
  148.   abort ();            /* die horribly */
  149. }
  150.  
  151. /* Copy string with CRLF newlines
  152.  * Accepts: destination string
  153.  *        pointer to size of destination string
  154.  *        source string
  155.  *        length of source string
  156.  */
  157.  
  158. char *strcrlfcpy (dst,dstl,src,srcl)
  159.     char **dst;
  160.     unsigned long *dstl;
  161.     char *src;
  162.     unsigned long srcl;
  163. {
  164.   long i,j;
  165.   char *d = src;
  166.                 /* count number of LF's in source string(s) */
  167.   for (i = srcl,j = 0; j < srcl; j++) if (*d++ == '\012') i++;
  168.   if (i > *dstl) {        /* resize if not enough space */
  169.     fs_give ((void **) dst);    /* fs_resize does an unnecessary copy */
  170.     *dst = (char *) fs_get ((*dstl = i) + 1);
  171.   }
  172.   d = *dst;            /* destination string */
  173.                 /* copy strings, inserting CR's before LF's */
  174.   while (srcl--) switch (*src) {
  175.   case '\015':            /* unlikely carriage return */
  176.     *d++ = *src++;        /* copy it and any succeeding linefeed */
  177.     if (srcl && *src == '\012') {
  178.       *d++ = *src++;
  179.       srcl--;
  180.     }
  181.     break;
  182.   case '\012':            /* line feed? */
  183.     *d++ ='\015';        /* yes, prepend a CR, drop into default case */
  184.   default:            /* ordinary chararacter */
  185.     *d++ = *src++;        /* just copy character */
  186.     break;
  187.   }
  188.   *d = '\0';            /* tie off destination */
  189.   return *dst;            /* return destination */
  190. }
  191.  
  192.  
  193. /* Length of string after strcrlflen applied
  194.  * Accepts: source string
  195.  *        length of source string
  196.  */
  197.  
  198. unsigned long strcrlflen (src,srcl)
  199.     char *src;
  200.     unsigned long srcl;
  201. {
  202.   long i = srcl;        /* look for LF's */
  203.   while (srcl--) switch (*src++) {
  204.   case '\015':            /* unlikely carriage return */
  205.     if (srcl && *src == '\012') { src++; srcl--; }
  206.     break;
  207.   case '\012':            /* line feed? */
  208.     i++;
  209.   default:            /* ordinary chararacter */
  210.     break;
  211.   }
  212.   return i;
  213. }
  214.  
  215. /* Server log in
  216.  * Accepts: user name string
  217.  *        password string
  218.  *        optional place to return home directory
  219.  * Returns: T if password validated, NIL otherwise
  220.  */
  221.  
  222. long server_login (user,pass,home)
  223.     char *user;
  224.     char *pass;
  225.     char **home;
  226. {
  227.   struct passwd *pw = getpwnam (lcase (user));
  228.                 /* no entry for this user or root */
  229.   if (!(pw && pw->pw_uid)) return NIL;
  230.                 /* validate password */
  231.   if (strcmp (pw->pw_passwd,(char *) crypt (pass,pw->pw_passwd))) return NIL;
  232.   setgid (pw->pw_gid);        /* all OK, login in as that user */
  233.   setuid (pw->pw_uid);
  234.                 /* note home directory */
  235.   if (home) *home = cpystr (pw->pw_dir);
  236.   return T;
  237. }
  238.  
  239. /* TCP/IP open
  240.  * Accepts: host name
  241.  *        contact port number
  242.  * Returns: TCP/IP stream if success else NIL
  243.  */
  244.  
  245. TCPSTREAM *tcp_open (host,port)
  246.     char *host;
  247.     long port;
  248. {
  249.   TCPSTREAM *stream = NIL;
  250.   int sock;
  251.   char *s;
  252.   struct sockaddr_in sin;
  253.   struct hostent *host_name;
  254.   char hostname[MAILTMPLEN];
  255.   char tmp[MAILTMPLEN];
  256.   /* The domain literal form is used (rather than simply the dotted decimal
  257.      as with other Unix programs) because it has to be a valid "host name"
  258.      in mailsystem terminology. */
  259.                 /* look like domain literal? */
  260.   if (host[0] == '[' && host[(strlen (host))-1] == ']') {
  261.     strcpy (hostname,host+1);    /* yes, copy number part */
  262.     hostname[(strlen (hostname))-1] = '\0';
  263.     if ((sin.sin_addr.s_addr = inet_addr (hostname)) != -1) {
  264.       sin.sin_family = AF_INET;    /* family is always Internet */
  265.       strcpy (hostname,host);    /* hostname is user's argument */
  266.     }
  267.     else {
  268.       sprintf (tmp,"Bad format domain-literal: %.80s",host);
  269.       mm_log (tmp,ERROR);
  270.       return NIL;
  271.     }
  272.   }
  273.  
  274.   else {            /* lookup host name, note that brain-dead Unix
  275.                    requires lowercase! */
  276.     strcpy (hostname,host);    /* in case host is in write-protected memory */
  277.     if ((host_name = gethostbyname (lcase (hostname)))) {
  278.                 /* copy address type */
  279.       sin.sin_family = host_name->h_addrtype;
  280.                 /* copy host name */
  281.       strcpy (hostname,host_name->h_name);
  282.                 /* copy host addresses */
  283.       memcpy (&sin.sin_addr,host_name->h_addr,host_name->h_length);
  284.     }
  285.     else {
  286.       sprintf (tmp,"No such host as %.80s",host);
  287.       mm_log (tmp,ERROR);
  288.       return NIL;
  289.     }
  290.   }
  291.  
  292.                 /* copy port number in network format */
  293.   if (!(sin.sin_port = htons (port))) fatal ("Bad port argument to tcp_open");
  294.                 /* get a TCP stream */
  295.   if ((sock = socket (sin.sin_family,SOCK_STREAM,0)) < 0) {
  296.     sprintf (tmp,"Unable to create TCP socket: %s",strerror (errno));
  297.     mm_log (tmp,ERROR);
  298.     return NIL;
  299.   }
  300.                 /* open connection */
  301.   if (connect (sock,(struct sockaddr *)&sin,sizeof (sin)) < 0) {
  302.     sprintf (tmp,"Can't connect to %.80s,%d: %s",hostname,port,
  303.          strerror (errno));
  304.     mm_log (tmp,ERROR);
  305.     return NIL;
  306.   }
  307.                 /* create TCP/IP stream */
  308.   stream = (TCPSTREAM *) fs_get (sizeof (TCPSTREAM));
  309.                 /* copy official host name */
  310.   stream->host = cpystr (hostname);
  311.                 /* get local name */
  312.   gethostname (tmp,MAILTMPLEN-1);
  313.   stream->localhost = cpystr ((host_name = gethostbyname (tmp)) ?
  314.                   host_name->h_name : tmp);
  315.                 /* init sockets */
  316.   stream->tcpsi = stream->tcpso = sock;
  317.   stream->ictr = 0;        /* init input counter */
  318.   return stream;        /* return success */
  319. }
  320.  
  321. /* TCP/IP authenticated open
  322.  * Accepts: host name
  323.  *        service name
  324.  * Returns: TCP/IP stream if success else NIL
  325.  */
  326.  
  327. TCPSTREAM *tcp_aopen (host,service)
  328.     char *host;
  329.     char *service;
  330. {
  331.   TCPSTREAM *stream = NIL;
  332.   struct hostent *host_name;
  333.   char hostname[MAILTMPLEN];
  334.   int i;
  335.   int pipei[2],pipeo[2];
  336.   /* The domain literal form is used (rather than simply the dotted decimal
  337.      as with other Unix programs) because it has to be a valid "host name"
  338.      in mailsystem terminology. */
  339.                 /* look like domain literal? */
  340.   if (host[0] == '[' && host[i = (strlen (host))-1] == ']') {
  341.     strcpy (hostname,host+1);    /* yes, copy without brackets */
  342.     hostname[i-1] = '\0';
  343.   }
  344.                 /* note that Unix requires lowercase! */
  345.   else if (host_name = gethostbyname (lcase (strcpy (hostname,host))))
  346.     strcpy (hostname,host_name->h_name);
  347.                 /* make command pipes */
  348.   if (pipe (pipei) < 0) return NIL;
  349.   if (pipe (pipeo) < 0) {
  350.     close (pipei[0]); close (pipei[1]);
  351.     return NIL;
  352.   }
  353.   if ((i = fork ()) < 0) {    /* make inferior process */
  354.     close (pipei[0]); close (pipei[1]);
  355.     close (pipeo[0]); close (pipeo[1]);
  356.     return NIL;
  357.   }
  358.   if (i) {            /* parent? */
  359.     close (pipei[1]);        /* close child's side of the pipes */
  360.     close (pipeo[0]);
  361.   }
  362.   else {            /* child */
  363.     dup2 (pipei[1],1);        /* parent's input is my output */
  364.     dup2 (pipei[1],2);        /* parent's input is my error output too */
  365.     close (pipei[0]); close (pipei[1]);
  366.     dup2 (pipeo[0],0);        /* parent's output is my input */
  367.     close (pipeo[0]); close (pipeo[1]);
  368.                 /* now run it */
  369.     execl ("/usr/ucb/remsh","remsh",hostname,"exec",service,0);
  370.     _exit (1);            /* spazzed */
  371.   }
  372.  
  373.                 /* create TCP/IP stream */
  374.   stream = (TCPSTREAM *) fs_get (sizeof (TCPSTREAM));
  375.                 /* copy official host name */
  376.   stream->host = cpystr (hostname);
  377.                 /* get local name */
  378.   gethostname (hostname,MAILTMPLEN-1);
  379.   stream->localhost = cpystr ((host_name = gethostbyname (hostname)) ?
  380.                   host_name->h_name : hostname);
  381.   stream->tcpsi = pipei[0];    /* init sockets */
  382.   stream->tcpso = pipeo[1];
  383.   stream->ictr = 0;        /* init input counter */
  384.   return stream;        /* return success */
  385. }
  386.  
  387. /* TCP/IP receive line
  388.  * Accepts: TCP/IP stream
  389.  * Returns: text line string or NIL if failure
  390.  */
  391.  
  392. char *tcp_getline (stream)
  393.     TCPSTREAM *stream;
  394. {
  395.   int n,m;
  396.   char *st;
  397.   char *ret;
  398.   char *stp;
  399.   char tmp[2];
  400.   fd_set fds;
  401.   FD_ZERO (&fds);        /* initialize selection vector */
  402.   if (stream->tcpsi < 0) return NIL;
  403.   while (stream->ictr < 1) {    /* if nothing in the buffer */
  404.     FD_SET (stream->tcpsi,&fds);/* set bit in selection vector */
  405.                 /* block and read */
  406.     if ((select (stream->tcpsi+1,&fds,0,0,0) < 0) ||
  407.     ((stream->ictr = read (stream->tcpsi,stream->ibuf,BUFLEN)) < 1)) {
  408.       close (stream->tcpsi);    /* nuke the socket */
  409.       if (stream->tcpsi != stream->tcpso) close (stream->tcpso);
  410.       stream->tcpsi = stream->tcpso = -1;
  411.       return NIL;
  412.     }
  413.     stream->iptr = stream->ibuf;/* point at TCP buffer */
  414.   }
  415.   st = stream->iptr;        /* save start of string */
  416.   n = 0;            /* init string count */
  417.   while (stream->ictr--) {    /* look for end of line */
  418.                 /* saw the trailing CR? */
  419.     if (stream->iptr++[0] == '\015') {
  420.       ret = (char *) fs_get (n+1);
  421.       memcpy (ret,st,n);    /* copy into a free storage string */
  422.       ret[n] = '\0';        /* tie off string with null */
  423.                 /* eat the line feed */
  424.       tcp_getbuffer (stream,1,tmp);
  425.       return ret;        /* return it to caller */
  426.     }
  427.     ++n;            /* else count and try next character */
  428.   }
  429.   stp = (char *) fs_get (n);    /* copy first part of string */
  430.   memcpy (stp,st,n);
  431.                 /* recurse to get remainder */
  432.   if (st = tcp_getline (stream)) {
  433.                 /* build total string */
  434.     ret = (char *) fs_get (n+1+(m = strlen (st)));
  435.     memcpy (ret,stp,n);        /* copy first part */
  436.     memcpy (ret+n,st,m);    /* and second part */
  437.     ret[n+m] = '\0';        /* tie off string with null */
  438.     fs_give ((void **) &st);    /* flush partial string */
  439.     fs_give ((void **) &stp);    /* flush initial fragment */
  440.   }
  441.   else ret = stp;        /* return the fragment */
  442.   return ret;
  443. }
  444.  
  445. /* TCP/IP receive buffer
  446.  * Accepts: TCP/IP stream
  447.  *        size in bytes
  448.  *        buffer to read into
  449.  * Returns: T if success, NIL otherwise
  450.  */
  451.  
  452. long tcp_getbuffer (stream,size,buffer)
  453.     TCPSTREAM *stream;
  454.     unsigned long size;
  455.     char *buffer;
  456. {
  457.   unsigned long n;
  458.   char *bufptr = buffer;
  459.   fd_set fds;
  460.   FD_ZERO (&fds);        /* initialize selection vector */
  461.   if (stream->tcpsi < 0) return NIL;
  462.   while (size > 0) {        /* until request satisfied */
  463.     while (stream->ictr < 1) {    /* if nothing in the buffer */
  464.       FD_SET (stream->tcpsi,&fds);
  465.                 /* block and read */
  466.       if ((select (stream->tcpsi+1,&fds,0,0,0) < 0) ||
  467.       ((stream->ictr = read (stream->tcpsi,stream->ibuf,BUFLEN)) < 1)) {
  468.     close (stream->tcpsi);    /* nuke the socket */
  469.     if (stream->tcpsi != stream->tcpso) close (stream->tcpso);
  470.     stream->tcpsi = stream->tcpso = -1;
  471.     return NIL;
  472.       }
  473.                 /* point at TCP buffer */
  474.       stream->iptr = stream->ibuf;
  475.     }
  476.     n = min (size,stream->ictr);/* number of bytes to transfer */
  477.                 /* do the copy */
  478.     memcpy (bufptr,stream->iptr,n);
  479.     bufptr += n;        /* update pointer */
  480.     stream->iptr +=n;
  481.     size -= n;            /* update # of bytes to do */
  482.     stream->ictr -=n;
  483.   }
  484.   bufptr[0] = '\0';        /* tie off string */
  485.   return T;
  486. }
  487.  
  488. /* TCP/IP send string as record
  489.  * Accepts: TCP/IP stream
  490.  * Returns: T if success else NIL
  491.  */
  492.  
  493. long tcp_soutr (stream,string)
  494.     TCPSTREAM *stream;
  495.     char *string;
  496. {
  497.   int i;
  498.   unsigned long size = strlen (string);
  499.   fd_set fds;
  500.   FD_ZERO (&fds);        /* initialize selection vector */
  501.   if (stream->tcpso < 0) return NIL;
  502.   while (size > 0) {        /* until request satisfied */
  503.     FD_SET (stream->tcpso,&fds);/* set bit in selection vector */
  504.     if ((select (stream->tcpso+1,0,&fds,0,0) < 0) ||
  505.     ((i = write (stream->tcpso,string,size)) < 0)) {
  506.       puts (strerror (errno));
  507.       close (stream->tcpsi);    /* nuke the socket */
  508.       if (stream->tcpsi != stream->tcpso) close (stream->tcpso);
  509.       stream->tcpsi = stream->tcpso = -1;
  510.       return NIL;
  511.     }
  512.     size -= i;            /* count this size */
  513.     string += i;
  514.   }
  515.   return T;            /* all done */
  516. }
  517.  
  518.  
  519. /* TCP/IP close
  520.  * Accepts: TCP/IP stream
  521.  */
  522.  
  523. void tcp_close (stream)
  524.     TCPSTREAM *stream;
  525. {
  526.  
  527.   if (stream->tcpsi >= 0) {    /* no-op if no socket */
  528.     close (stream->tcpsi);    /* nuke the socket */
  529.     if (stream->tcpsi != stream->tcpso) close (stream->tcpso);
  530.     stream->tcpsi = stream->tcpso = -1;
  531.   }
  532.                 /* flush host names */
  533.   fs_give ((void **) &stream->host);
  534.   fs_give ((void **) &stream->localhost);
  535.   fs_give ((void **) &stream);    /* flush the stream */
  536. }
  537.  
  538. /* TCP/IP get host name
  539.  * Accepts: TCP/IP stream
  540.  * Returns: host name for this stream
  541.  */
  542.  
  543. char *tcp_host (stream)
  544.     TCPSTREAM *stream;
  545. {
  546.   return stream->host;        /* return host name */
  547. }
  548.  
  549.  
  550. /* TCP/IP get local host name
  551.  * Accepts: TCP/IP stream
  552.  * Returns: local host name
  553.  */
  554.  
  555. char *tcp_localhost (stream)
  556.     TCPSTREAM *stream;
  557. {
  558.   return stream->localhost;    /* return local host name */
  559. }
  560.  
  561.  
  562.  
  563. /* Return pointer to first occurance in string of a substring
  564.  * Accepts: source pointer
  565.  *        substring pointer
  566.  * Returns: pointer to substring in source or NIL if not found
  567.  */
  568.  
  569. char *strstr (cs,ct)
  570.      char *cs;
  571.      char *ct;
  572. {
  573.   char *s;
  574.   char *t;
  575.   while (cs = index (cs,*ct)) {    /* for each occurance of the first character */
  576.                 /* see if remainder of string matches */
  577.     for (s = cs + 1, t = ct + 1; *t && *s == *t; s++, t++);
  578.     if (!*t) return cs;        /* if ran out of substring then have match */
  579.     cs++;            /* try from next character */
  580.   }
  581.   return NIL;            /* not found */
  582. }
  583.  
  584. /* Return implementation-defined string corresponding to error
  585.  * Accepts: error number
  586.  * Returns: string for that error
  587.  */
  588.  
  589. char *strerror (n)
  590.      int n;
  591. {
  592.   extern char *sys_errlist[];
  593.   extern int sys_nerr;
  594.  
  595.   return (n >= 0 && n < sys_nerr) ? sys_errlist[n] : NIL;
  596. }
  597.  
  598.  
  599. /*
  600.  * Turn a string long into the real thing
  601.  * Accepts: source string
  602.  *        pointer to place to return end pointer
  603.  *        base
  604.  * Returns: parsed long integer, end pointer is updated
  605.  */
  606.  
  607. long strtol (s,endp,base)
  608.      char *s;
  609.      char **endp;
  610.      int base;
  611. {
  612.   long value = 0;        /* the accumulated value */
  613.   int negative = 0;        /* this a negative number? */
  614.   int ok;            /* true while valid chars for number */
  615.   char c;
  616.                 /* insist upon valid base */
  617.   if (base && (base < 2 || base > 36)) return NIL;
  618.   while (isspace (*s)) s++;    /* skip leading whitespace */
  619.   if (!base) {            /* if base = 0, */
  620.     if (*s == '-') {        /* integer constants are allowed a */
  621.       negative = 1;        /* leading unary minus, but not */
  622.       s++;            /* unary plus. */
  623.     }
  624.     else negative = 0;
  625.     if (*s == '0') {        /* if it starts with 0, its either */
  626.                 /* 0X, which marks a hex constant, */
  627.       if (toupper (*++s) == 'X') {
  628.     s++;            /* skip the X */
  629.            base = 16;        /* base is hex 16 */
  630.       }
  631.       else base = 8;        /* leading 0 means octal number */
  632.     }
  633.     else base = 10;        /* otherwise, decimal. */
  634.     do {
  635.       switch (base) {        /* char has to be valid for base */
  636.       case 8:            /* this digit ok? */
  637.     ok = isodigit(*s);
  638.     break;
  639.       case 10:
  640.     ok = isdigit(*s);
  641.     break;
  642.       case 16:
  643.     ok = isxdigit(*s);
  644.     break;
  645.       default:            /* it's good form you know */
  646.     return NIL;
  647.       }
  648.                 /* if valid char, accumulate */
  649.       if (ok) value = value * base + toint(*s++);
  650.     } while (ok);
  651.     if (toupper(*s) == 'L') s++;/* ignore 'l' or 'L' marker */
  652.     if (endp) *endp = s;    /* set user pointer to after num */
  653.     return (negative) ? -value : value;
  654.   }
  655.  
  656.   switch (*s) {            /* check for leading sign char */
  657.   case '-':
  658.     negative = 1;        /* yes, negative #.  fall into '+' */
  659.   case '+':
  660.     s++;            /* skip the sign character */
  661.   }
  662.                 /* allow hex prefix "0x" */
  663.   if (base == 16 && *s == '0' && toupper (*(s + 1)) == 'X') s += 2;
  664.   do {
  665.                 /* convert to numeric form if digit*/
  666.     if (isdigit (*s)) c = toint (*s);
  667.                 /* alphabetic conversion */
  668.     else if (isalpha (*s)) c = *s - (isupper (*s) ? 'A' : 'a') + 10;
  669.     else break;            /* else no way it's valid */
  670.     if (c >= base) break;    /* digit out of range for base? */
  671.     value = value * base + c;    /* accumulate the digit */
  672.   } while (*++s);        /* loop until non-numeric character */
  673.   if (endp) *endp = s;        /* save users endp to after number */
  674.                 /* negate number if needed */
  675.   return (negative) ? -value : value;
  676. }
  677.  
  678. /* Emulator for BSD re_comp() call
  679.  * Accepts: character string to compile
  680.  * Returns: 0 if successful, else error message
  681.  * Uses the regcomp(3C) libraries.
  682.  */
  683.  
  684. regex_t preg ;
  685.  
  686. char *re_comp(str)
  687.   char *str ;
  688.   {
  689.   static char *invalstr = "invalid string" ;
  690.   return regcomp(&preg, str, 0) ? 0 : invalstr ;
  691.   }
  692.  
  693. /* Emulator for BSD re_exec() call
  694.  * Accepts : string to match
  695.  * Returns: 1 if string matches, 0 if fails to match
  696.  */
  697.  
  698. long re_exec(str)
  699.   char *str ;
  700.   {
  701.   if (regexec(&preg, str, (size_t) 0, NULL)) return 1 ; else return 0 ;  
  702.   }
  703.  
  704.  
  705. /* Emulator for BSD flock() call
  706.  * Accepts: file descriptor
  707.  *        operation bitmask
  708.  * Returns: 0 if successful, -1 if failure
  709.  * Note: this emulator does not handle shared locks
  710.  */
  711.  
  712. int flock (fd, operation)
  713.     int fd;
  714.     int operation;
  715. {
  716.   int func;
  717.                 /* translate to flock() operation */
  718.   if (operation & LOCK_UN) func = F_ULOCK;
  719.   else if (operation & (LOCK_EX|LOCK_SH))
  720.     func = (operation & LOCK_NB) ? F_TLOCK : F_LOCK;
  721.   else {
  722.     errno = EINVAL;
  723.     return -1;
  724.   }
  725.   return lockf (fd,func,0);    /* do the lockf() */
  726. }
  727.  
  728.  
  729. /* Emulator for BSD utimes() call
  730.  * Accepts: file name
  731.  *        timeval vector for access and updated time
  732.  * Returns: 0 if successful, -1 if failure
  733.  */
  734.  
  735. int utimes (file,tvp)
  736.     char *file;
  737.     struct timeval tvp[2];
  738. {
  739.   struct utimbuf tb;
  740.   tb.actime = tvp[0].tv_sec;    /* accessed time */
  741.   tb.modtime = tvp[1].tv_sec;    /* updated time */
  742.   return utime (file,&tb);
  743. }
  744.  
  745. /* Emulator for BSD random() call
  746.  * Returns: a random number between 0 and 2^31
  747.  */
  748.  
  749. long random()
  750.   {
  751.   return lrand48() ;
  752.   }
  753.  
  754.  
  755. /* Emulator for BSD gethostid() call
  756.  * Returns: a unique identifier for the system.  
  757.  * Even though HP/UX has an undocumented gethostid() system call,
  758.  * it does not work (at least for non-priviliged users).  
  759.  */
  760.  
  761. #include <sys/utsname.h>
  762.  
  763. struct utsname udata ;
  764.  
  765. long gethostid()
  766.   {
  767.   if (uname(&udata))
  768.     return 0 ;
  769.   return atol(udata.idnumber) ;
  770.   }
  771.  
  772.  
  773.  
  774.